export interface CartItem {
  id: number;
  quantity: number;
  product: {
    id: number;
    name: string;
    price: number;
    image?: string;
  };
}

export async function addToCart(productId: number, quantity: number, sessionId: string) {
  const response = await fetch('/api/cart', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ productId, quantity, sessionId }),
  });
  
  if (!response.ok) {
    throw new Error('Failed to add to cart');
  }
  return response.json();
}

export async function getCart(sessionId: string): Promise<CartItem[]> {
  const response = await fetch(`/api/cart?sessionId=${sessionId}`);
  if (!response.ok) {
    return [];
  }
  const data = await response.json();
  return data.items || [];
}

export async function removeFromCart(itemId: number) {
  const response = await fetch('/api/cart', {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ id: itemId }),
  });
  
  if (!response.ok) {
    throw new Error('Failed to remove from cart');
  }
  return response.json();
}